package com.googlecode.thriftbenchmark.size;

import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.protocol.TJSONProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TMemoryBuffer;

import com.googlecode.thriftbenchmark.twitter.Tweet;
import com.googlecode.thriftbenchmark.twitter.TweetFactory;
import com.googlecode.thriftbenchmark.twitterprotoc.TweetProtocFactory;
import com.googlecode.thriftbenchmark.twitterprotoc.Twitter.TweetProtoc;


/**
 * Benchmark the serialized data size in different TProtocols.
 * 
 * @author Li Weibo (weibo.leo@gmail.com) //I believe spring-brother
 */
public class SizeBenchmark {

    private TMemoryBuffer toBinary(Tweet t) throws TException {
        TMemoryBuffer buffer = new TMemoryBuffer(128);
        TProtocol protocol = new TBinaryProtocol(buffer);
        t.write(protocol);
        return buffer;
    }
    
    private TMemoryBuffer toJson(Tweet t) throws TException {
        TMemoryBuffer buffer = new TMemoryBuffer(128);
        TProtocol protocol = new TJSONProtocol(buffer);
        t.write(protocol);
        return buffer;
    }
    
    private TMemoryBuffer toCompact(Tweet t) throws TException {
        TMemoryBuffer buffer = new TMemoryBuffer(128);
        TProtocol protocol = new TCompactProtocol(buffer);
        t.write(protocol);
        return buffer;
    }
    
    private byte[] toProtobuffBytes(TweetProtoc tp) {
        return tp.toByteArray();
    }
    
    
    public static void main(String[] args) throws Exception {
        
        SizeBenchmark app = new SizeBenchmark();
        TweetFactory fact = new TweetFactory();
        Tweet t = fact.randomTweet();
        System.out.println("Bin : " + app.toBinary(t).length());
        System.out.println("Json: " + app.toJson(t).length());
        System.out.println("Comp: " + app.toCompact(t).length());
        
        TweetProtocFactory tpFact = new TweetProtocFactory();
        TweetProtoc tp = tpFact.randomTweet(); 
        tp = tp.toBuilder().setText(t.getText()).build();
        
        System.out.println("Protoc: " + app.toProtobuffBytes(tp).length);
    }
    
}
